package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 韩先楚
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 添加购物车
     * @return
     */
    public void addCart(ShoppingCartDTO dto) {
        //先判断购物车是否存在，如果存在，则更新数量，如果不存在，则新增购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto,shoppingCart);
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();
         shoppingCart.setUserId(userId);
         //判断购物车是否存在
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list!=null && list.size()>0)
        {
            //存在，则更新数量
            ShoppingCart cart = list.get(0);
            Long id = cart.getId();
            //更新数量
            shoppingCartMapper.add(id);
            return;
        }
        //不存在，则新增购物车,先判断类型是菜品还是套餐
        if (dto.getDishId()==null)
        {
            long setmealId = dto.getSetmealId();
            //为套餐
            SetmealVO setmealById = setmealMapper.getSetmealById((int)setmealId);
             shoppingCart.setName(setmealById.getName());
             shoppingCart.setImage(setmealById.getImage());
             shoppingCart.setAmount(setmealById.getPrice());
        }
        else {
            //为菜品
            long dishId = dto.getDishId();
            Dish dish = dishMapper.deleteById((int) dishId);
            shoppingCart.setName(dish.getName());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setAmount(dish.getPrice());
        }
        //新增购物车 数量为1
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCartMapper.save(shoppingCart);
    }

    /**
     * 查询用户的购物车
     */
    public List<ShoppingCart> list() {
        ShoppingCart build = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();

        List<ShoppingCart> list = shoppingCartMapper.list(build);
        return list;
    }

    /**
     *
     * 清空购物车
     */
    public void clean() {
        shoppingCartMapper.clean(BaseContext.getCurrentId());
    }
}
